package com.dlc.shop.sys.platform.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import com.dlc.shop.bean.enums.EsOperationType;
import com.dlc.shop.bean.enums.ProdStatusEnums;
import com.dlc.shop.bean.enums.SigningStatus;
import com.dlc.shop.bean.event.EsProductUpdateEvent;
import com.dlc.shop.bean.model.Product;
import com.dlc.shop.bean.model.SigningAuditing;
import com.dlc.shop.common.annotation.SysLog;
import com.dlc.shop.common.bean.SysConfig;
import com.dlc.shop.common.bean.SysProdConfig;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.i18n.I18nMessage;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.Json;
import com.dlc.shop.service.CategoryShopService;
import com.dlc.shop.service.ProductService;
import com.dlc.shop.service.SigningAuditingService;
import com.dlc.shop.service.SysConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品配置审核
 * @author zp
 */
@Tag(name = "商品配置审核")
@RestController
@RequestMapping("/sys/audit")
@RequiredArgsConstructor
public class SysAuditController {

    @Value("${yami.expose.operation.auth:}")
    private Boolean permission;

    private final SysConfigService sysConfigService;
    private final ProductService productService;
    private final ApplicationEventPublisher eventPublisher;
    private final SigningAuditingService signingAuditingService;
    private final CategoryShopService categoryShopService;


    @SysLog("获取配置信息")
    @GetMapping("/signingConfig")
    @Operation(summary = "获取签约审核配置信息" , description = "获取签约审核配置信息")
    @PreAuthorize("@pms.hasPermission('sys:audit:info')")
    public ServerResponseEntity<String> info(){
        return ServerResponseEntity.success(sysConfigService.getValue(Constant.PROD_SWITCH_CONFIG));
    }

    @SysLog("保存配置")
    @PostMapping("/save")
    @Operation(summary = "保存配置" , description = "保存配置")
    @PreAuthorize("@pms.hasPermission('sys:audit:save')")
    public ServerResponseEntity<Void> save(@RequestBody @Valid SysConfig sysConfig){
        if (BooleanUtil.isFalse(permission)) {
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.operate.auth"));
        }
        String paramValue = sysConfig.getParamValue();
        String paramKey = sysConfig.getParamKey();
        if (Objects.equals(paramKey, Constant.PROD_SWITCH_CONFIG)) {
            SysProdConfig dbProdConfig = sysConfigService.getSysConfigObject(paramKey, SysProdConfig.class);
            sysConfigService.updateValueByKey(paramKey,paramValue);
            sysConfigService.removeSysConfig(paramKey);
            SysProdConfig sysProdConfig = Json.parseObject(paramValue, SysProdConfig.class);
            // 判断处理商品审核和签约类目审核
            // 判断是否关闭
            if (!Objects.equals(dbProdConfig.getProdAudit(), sysProdConfig.getProdAudit()) && !sysProdConfig.getProdAudit()) {
                // 获取所有待审核状态的商品
                List<Product> products = productService.listProdByAutidStatus();
                if (CollectionUtil.isNotEmpty(products)) {
                    // 更新待审核商品状态为上架
                    products.forEach(product -> product.setStatus(ProdStatusEnums.NORMAL.getValue()));
                    productService.updateBatchById(products);
                    // 移除缓存
                    List<Long> prodIds = products.stream().map(Product::getProdId).collect(Collectors.toList());
                    productService.removeProductCacheByProdIds(prodIds);
                    eventPublisher.publishEvent(new EsProductUpdateEvent(null, prodIds, EsOperationType.UPDATE_BATCH));
                }
            }
            if (!Objects.equals(dbProdConfig.getSigningAudit(), sysProdConfig.getSigningAudit()) && !sysProdConfig.getSigningAudit()) {
                // 获取所有待审核状态的签约审核信息
                List<SigningAuditing> signingAuditings = signingAuditingService.listAuditingByAutidStatus();
                if (CollectionUtil.isNotEmpty(signingAuditings)) {
                    for (SigningAuditing signingAuditing : signingAuditings) {
                        signingAuditing.setStatus(SigningStatus.SUCCESS.value());
                        // 更新店铺待审核的签约类目
                        categoryShopService.changeStatusByShopIdAndStatus(signingAuditing.getShopId(), SigningStatus.PENDING_REVIEW.value(), SigningStatus.SUCCESS.value());
                    }
                    signingAuditingService.updateBatchById(signingAuditings);
                }
            }
        }
        return ServerResponseEntity.success();
    }

}
